#!/usr/local/bin/perl
#This script is used to replace the variables in the template file with the values in the global.properties file to get a new file.
#Run this script: ./replace.pl <template file> <the file generated after replacement>
#For example: ./replace.pl index.html.tmpl index.html 
#Note: the charset in the html file needs to be changed manually accordingly after this script is run. For example, if the replacement is to convert the page to Chineses language, then the charset should be modified to "charset=gb2312"
#Author: Nick
#Date: 12/22/2009.

use strict;
use warnings;

if(!(-d "./locale"))
{
	system("mkdir locale"); 
}

opendir(DIR, "."); 

my @html_files = (
	"aniweather.config7.html" 
	# "index.html"
	);
	
sub create_pages
{
	my $path = $_[0]; 
	
	my $html_file; 
	my %variables = ();
	my $variable_file="global.properties";
	
	my $opened = open (v_fh, "<$path/$variable_file");
	if(! $opened)
	{
		# print "Skipping $path (not valid)...\n";
		return; 
	}
	
	if(!(-d "./locale/$path"))
	{
		system("mkdir \"./locale/$path\""); 
	}	
	
	while (<v_fh>) {
		if (/(.+)=(.+)/) {
			my $key=$1;
			my $value=$2;
			$variables{$key}=$value;
		}
	}
	close v_fh;
		
	print "  $path... ";
	foreach $html_file (@html_files)
	{
		print "$html_file... ";
		my $new_html_file = "locale/$path/$html_file";

		open (h_fh, "<$html_file.tmpl") or die "Can't open $html_file.tmpl: $!";
		unlink ($new_html_file); 
		
		open (nh_fh,">>$new_html_file") or die "Can't open $new_html_file";
		while(<h_fh>){
			my $line=$_;
			while ( my ($key, $value) = each(%variables) ) {			
				if ($line =~ /\[\[$key\]\]/){
					$line =~ s/\[\[$key\]\]/$value/g;
				}		
			}
			#print "the line is: $line\n";
			print nh_fh "$line";
		}
		close nh_fh;
	}
	print "Done!!!\n";
}
	
my @aryFolders = readdir(DIR); 
my $folder; 
foreach $folder (@aryFolders)
{
	create_pages($folder);
}	
